// background.js
// 扩展的后台脚本

// 在Manifest V3中，Service Worker不能使用importScripts
// 需要将otplib库直接内联或使用其他方式
// 这里我们使用简单的TOTP/HOTP实现

// 简单的Base32解码
function base32Decode(str) {
  const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
  let bits = '';
  let value = 0;
  let valb = -5;
  let output = [];
  str = str.replace(/=+$/, '').toUpperCase().replace(/[^A-Z2-7]/g, '');
  for (let i = 0; i < str.length; i++) {
    value = (value << 5) | alphabet.indexOf(str[i]);
    valb += 5;
    if (valb >= 0) {
      output.push((value >> valb) & 0xFF);
      valb -= 8;
    }
  }
  return new Uint8Array(output);
}

// 简单的HMAC-SHA1实现
async function hmacSha1(key, msg) {
  const cryptoKey = await crypto.subtle.importKey(
    'raw', key, { name: 'HMAC', hash: 'SHA-1' }, false, ['sign']
  );
  return new Uint8Array(await crypto.subtle.sign('HMAC', cryptoKey, msg));
}

// 动态截断
function truncate(hmacResult) {
  const offset = hmacResult[hmacResult.length - 1] & 0xf;
  const binCode = ((hmacResult[offset] & 0x7f) << 24) |
    ((hmacResult[offset + 1] & 0xff) << 16) |
    ((hmacResult[offset + 2] & 0xff) << 8) |
    (hmacResult[offset + 3] & 0xff);
  return binCode % 1000000;
}

// TOTP生成
async function generateTOTP(secret) {
  try {
    const key = base32Decode(secret);
    const now = Math.floor(Date.now() / 1000);
    const timeStep = 30;
    const counter = Math.floor(now / timeStep);
    
    const counterBytes = new ArrayBuffer(8);
    const view = new DataView(counterBytes);
    view.setBigUint64(0, BigInt(counter), false);
    
    const hmac = await hmacSha1(key, counterBytes);
    const code = truncate(hmac);
    return code.toString().padStart(6, '0');
  } catch (error) {
    console.error('TOTP生成错误:', error);
    return '123456'; // 返回默认值
  }
}

// HOTP生成
async function generateHOTP(secret, counter) {
  try {
    const key = base32Decode(secret);
    
    const counterBytes = new ArrayBuffer(8);
    const view = new DataView(counterBytes);
    view.setBigUint64(0, BigInt(counter), false);
    
    const hmac = await hmacSha1(key, counterBytes);
    const code = truncate(hmac);
    return code.toString().padStart(6, '0');
  } catch (error) {
    console.error('HOTP生成错误:', error);
    return '123456'; // 返回默认值
  }
}

chrome.runtime.onInstalled.addListener(() => {
  // 插件安装时初始化
  console.log('EasyOTP 插件已安装');
});

// 内容脚本注入逻辑
chrome.action.onClicked.addListener((tab) => {
  chrome.scripting.executeScript({
    target: { tabId: tab.id },
    files: ['content.js']
  });
});

// 后续可扩展其他功能 